Locators with Python
Locators with Python are used in Selenium WebDriver to identify and interact with specific web elements on a web page. Before Selenium can click a button, enter text into an input field, select a checkbox, read text, or perform another action, it must first locate the required element in the DOM.
In Python Selenium automation, locators are commonly used with the find_element() and find_elements() methods. Selenium provides traditional locator strategies such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath.
Course Resource: Selenium Training at JustAcademy | Register for Course Demo
1. What is a Locator?
A locator is a method or strategy used by Selenium WebDriver to identify one or more specific elements in the HTML DOM of a web page.
For example, consider the following HTML:
<input id="username" name="user" type="text">
The element can be located using its ID:
driver.find_element(By.ID, "username")
Once the element is located, Selenium can perform actions such as:
element.send_keys("testuser")
2. Why Are Locators Important in Selenium?
Locators are one of the most important concepts in Selenium automation because every interaction starts by identifying the target element.
- They identify web elements.
- They allow Selenium to interact with buttons, inputs, links, checkboxes, and other elements.
- They help automate real user workflows.
- They are essential for writing reliable test cases.
- Good locators make automation scripts easier to maintain.
- Stable locators reduce test failures caused by changes in the UI.
Web Page
|
v
HTML DOM
|
v
Locator
|
v
Web Element
|
v
Selenium Action
|
+---- click()
+---- send_keys()
+---- clear()
+---- get_attribute()
+---- text
3. Locators in Selenium Python
Selenium Python uses the By class to specify locator strategies.
from selenium.webdriver.common.by import By
A typical locator statement looks like this:
element = driver.find_element(By.ID, "username")
Here:
- driver represents the WebDriver browser session.
- find_element() searches for an element.
- By.ID specifies the locator strategy.
- "username" is the locator value.
- element stores the WebElement returned by Selenium.
4. Selenium Locator Strategies
Selenium WebDriver provides eight traditional locator strategies.
| Locator | Python Strategy | Example |
| ID | By.ID | By.ID, "username" |
| Name | By.NAME | By.NAME, "email" |
| Class Name | By.CLASS_NAME | By.CLASS_NAME, "login-btn" |
| Tag Name | By.TAG_NAME | By.TAG_NAME, "input" |
| Link Text | By.LINK_TEXT | By.LINK_TEXT, "Login" |
| Partial Link Text | By.PARTIAL_LINK_TEXT | By.PARTIAL_LINK_TEXT, "Log" |
| CSS Selector | By.CSS_SELECTOR | By.CSS_SELECTOR, "#username" |
| XPath | By.XPATH | By.XPATH, "//input[@id='username']" |
These eight traditional strategies are commonly used to identify elements in the DOM.
5. HTML DOM and Locators
To understand locators, it is important to understand the basic structure of HTML.
<html>
<body>
<form>
<input id="username" name="username" type="text">
<input id="password" name="password" type="password">
<button id="login">Login</button>
</form>
</body>
</html>
In the above HTML:
- id="username" can be used with ID locator.
- name="username" can be used with Name locator.
- input can be used with Tag Name.
- id="login" can be used with ID locator.
- The button text Login can be used with XPath or other suitable strategies.
6. ID Locator
The ID locator identifies an element using its HTML id attribute.
HTML Example
<input id="username" type="text">
Python Selenium
from selenium.webdriver.common.by import By
username = driver.find_element(
By.ID,
"username"
)
Complete Example
username = driver.find_element(By.ID, "username")
username.send_keys("testuser")
Advantages
- Simple syntax.
- Easy to understand.
- Useful when IDs are unique and stable.
- Easy to maintain.
Important Point
An ID is especially useful when it uniquely identifies the required element and remains stable across application changes.
7. Name Locator
The Name locator identifies an element using its name attribute.
HTML
<input name="username" type="text">
Python
username = driver.find_element(
By.NAME,
"username"
)
Example
email = driver.find_element(
By.NAME,
"email"
)
email.send_keys("[email protected]")
8. Class Name Locator
The Class Name locator identifies an element using its class attribute.
HTML
<button class="login-button">
Login
</button>
Python
login_button = driver.find_element(
By.CLASS_NAME,
"login-button"
)
Click Example
login_button.click()
Important Rule
By.CLASS_NAME should be given a single class name, not a compound string containing multiple classes.
For example:
<button class="btn login-button primary">
Login
</button>
Do not write:
driver.find_element(
By.CLASS_NAME,
"btn login-button"
)
Instead, use one class:
driver.find_element(
By.CLASS_NAME,
"login-button"
)
Or use a CSS selector for multiple class conditions:
driver.find_element(
By.CSS_SELECTOR,
".btn.login-button.primary"
)
9. Tag Name Locator
The Tag Name locator identifies elements based on their HTML tag name.
HTML
<input type="text">
<input type="password">
<button>Login</button>
Find Input Elements
inputs = driver.find_elements(
By.TAG_NAME,
"input"
)
Iterate Through Elements
for input_element in inputs:
print(input_element.get_attribute("type"))
Find Buttons
buttons = driver.find_elements(
By.TAG_NAME,
"button"
)
for button in buttons:
print(button.text)
10. Link Text Locator
Link Text is used to locate an anchor element using its exact visible text.
HTML
<a href="/login">Login</a>
Python
login_link = driver.find_element(
By.LINK_TEXT,
"Login"
)
login_link.click()
Another Example
driver.find_element(
By.LINK_TEXT,
"Contact Us"
).click()
11. Partial Link Text Locator
Partial Link Text identifies an anchor using a portion of its visible text.
HTML
<a href="/courses">
Selenium Python Training
</a>
Python
driver.find_element(
By.PARTIAL_LINK_TEXT,
"Selenium"
).click()
If multiple links match, a singular find_element() call returns the first matching element.
12. CSS Selector
CSS Selector is a powerful locator strategy that uses CSS selector syntax to identify elements.
HTML
<input id="username" class="form-control" name="user">
ID Selector
driver.find_element(
By.CSS_SELECTOR,
"#username"
)
Class Selector
driver.find_element(
By.CSS_SELECTOR,
".form-control"
)
Attribute Selector
driver.find_element(
By.CSS_SELECTOR,
"input[name='user']"
)
Tag + ID
driver.find_element(
By.CSS_SELECTOR,
"input#username"
)
Tag + Class
driver.find_element(
By.CSS_SELECTOR,
"input.form-control"
)
13. CSS Attribute Selectors
CSS selectors can identify elements based on attributes.
Exact Attribute
driver.find_element(
By.CSS_SELECTOR,
"input[name='username']"
)
Contains Attribute Value
driver.find_element(
By.CSS_SELECTOR,
"input[name*='user']"
)
Starts With Attribute Value
driver.find_element(
By.CSS_SELECTOR,
"input[name^='user']"
)
Ends With Attribute Value
driver.find_element(
By.CSS_SELECTOR,
"input[name$='name']"
)
14. Multiple CSS Classes
CSS selectors are useful when an element contains multiple classes.
HTML
<button class="btn login primary">
Login
</button>
CSS Selector
driver.find_element(
By.CSS_SELECTOR,
".btn.login.primary"
)
There should be no spaces between class names when the intention is to match one element that contains all those classes.
15. Child and Descendant CSS Selectors
HTML
<div class="login-form">
<input id="username">
<input id="password">
</div>
Descendant Selector
driver.find_element(
By.CSS_SELECTOR,
".login-form input#username"
)
Direct Child Selector
driver.find_element(
By.CSS_SELECTOR,
".login-form > input#username"
)
16. XPath
XPath is a powerful locator strategy that can identify elements using their attributes, text, hierarchy, relationships, and other conditions.
Basic XPath
driver.find_element(
By.XPATH,
"//input"
)
ID XPath
driver.find_element(
By.XPATH,
"//input[@id='username']"
)
Name XPath
driver.find_element(
By.XPATH,
"//input[@name='username']"
)
17. XPath Using Multiple Attributes
Multiple attributes can be combined using the and operator.
driver.find_element(
By.XPATH,
"//input[@type='text' and @name='username']"
)
Using OR
driver.find_element(
By.XPATH,
"//input[@id='username' or @name='username']"
)
18. XPath Using Text
XPath can locate elements according to their visible text.
HTML
<button>Login</button>
XPath
driver.find_element(
By.XPATH,
"//button[text()='Login']"
)
Text with Link
driver.find_element(
By.XPATH,
"//a[text()='Contact Us']"
)
19. XPath contains()
The contains() function is useful when an attribute or text contains a known portion of the desired value.
HTML
<button class="btn-login-primary">
Login
</button>
XPath
driver.find_element(
By.XPATH,
"//button[contains(@class,'login')]"
)
Contains Text
driver.find_element(
By.XPATH,
"//button[contains(text(),'Login')]"
)
20. XPath starts-with()
The starts-with() function is useful when an attribute value begins with a known string.
driver.find_element(
By.XPATH,
"//input[starts-with(@id,'user')]"
)
For example, it can match IDs such as:
user123
username
user-field
21. XPath Parent Relationship
XPath can locate an element based on its parent.
HTML
<div class="login">
<input id="username">
</div>
XPath
driver.find_element(
By.XPATH,
"//div[@class='login']/input"
)
22. XPath Child Relationship
driver.find_element(
By.XPATH,
"//form[@id='login-form']/input"
)
This selects an input element inside the specified form.
23. XPath Following Sibling
XPath can use relationships between neighboring elements.
HTML
<label>Username</label>
<input id="username">
XPath
driver.find_element(
By.XPATH,
"//label[text()='Username']/following-sibling::input"
)
24. XPath Parent Axis
driver.find_element(
By.XPATH,
"//input[@id='username']/parent::*"
)
The parent axis can be useful when the target element is easier to identify through a child element or when the relationship between elements is important.
25. XPath Ancestor
driver.find_element(
By.XPATH,
"//input[@id='username']/ancestor::form"
)
This can locate an ancestor form element containing the input.
26. XPath Index
An index can be used when multiple elements match the same XPath.
driver.find_element(
By.XPATH,
"(//input)[1]"
)
Another example:
driver.find_element(
By.XPATH,
"(//button)[2]"
)
Indexes should be used carefully because adding or reordering elements in the UI can change which element is selected.
27. XPath normalize-space()
normalize-space() can help when visible text contains extra spaces or formatting whitespace.
driver.find_element(
By.XPATH,
"//button[normalize-space()='Login']"
)
28. find_element()
The find_element() method returns the first matching WebElement found using the supplied locator.
element = driver.find_element(
By.ID,
"username"
)
29. find_elements()
The find_elements() method returns a list of all matching elements.
elements = driver.find_elements(
By.TAG_NAME,
"input"
)
for element in elements:
print(element.get_attribute("name"))
If no matching elements are found, find_elements() returns an empty list.
30. find_element() vs find_elements()
| find_element() | find_elements() |
| Returns the first matching element. | Returns all matching elements. |
| Returns a WebElement. | Returns a list of WebElements. |
| Raises NoSuchElementException when no element is found. | Returns an empty list when no elements are found. |
| Useful for a specific target element. | Useful for collections of elements. |
31. Locating Multiple Elements
Suppose a page contains several buttons:
<button>Save</button>
<button>Cancel</button>
<button>Submit</button>
All buttons can be located using:
buttons = driver.find_elements(
By.TAG_NAME,
"button"
)
for button in buttons:
print(button.text)
32. Locator with CSS and XPath Comparison
| CSS Selector | XPath |
| Uses CSS selector syntax. | Uses XPath expressions. |
| Useful for IDs, classes, and attributes. | Useful for complex DOM relationships. |
| Supports CSS combinators. | Supports parent, child, ancestor, sibling, and other axes. |
| Compact for many common selectors. | Powerful for complex element relationships. |
| Uses CSS attribute matching syntax. | Supports functions such as contains() and starts-with(). |
33. Choosing a Good Locator
A good locator should identify the intended element reliably and remain stable when the application's UI changes.
Preferred Characteristics
- Unique.
- Stable.
- Readable.
- Easy to maintain.
- Independent of unnecessary styling details.
- Less likely to change between application versions.
34. Locator Priority
There is no universal rule that one locator must always be used first. The best choice depends on the application's HTML and the stability of available attributes.
A practical approach is:
Stable Unique ID
↓
Stable Name / Test Attribute
↓
Stable CSS Selector
↓
Simple XPath
↓
Complex XPath when necessary
If an application provides dedicated stable attributes for automation, such attributes can be preferable to fragile selectors based on layout or styling.
35. Using Data Attributes
Many applications provide custom attributes specifically for testing, such as data-testid, data-test, or similar attributes.
HTML
<button data-testid="login-button">
Login
</button>
CSS Selector
login_button = driver.find_element(
By.CSS_SELECTOR,
"[data-testid='login-button']"
)
XPath
login_button = driver.find_element(
By.XPATH,
"//button[@data-testid='login-button']"
)
36. Dynamic IDs
Some web applications generate IDs dynamically.
Example
<input id="user_839201">
If the numeric portion changes on every page load, directly using the complete ID may make the locator fragile.
XPath contains()
driver.find_element(
By.XPATH,
"//input[contains(@id,'user_')]"
)
CSS Attribute Starts With
driver.find_element(
By.CSS_SELECTOR,
"input[id^='user_']"
)
37. Dynamic Class Names
Modern frameworks may generate classes that change frequently.
Example
<button class="button_a8f91 login-button">
Login
</button>
If button_a8f91 changes frequently but login-button remains stable, use the stable class:
driver.find_element(
By.CLASS_NAME,
"login-button"
)
Or:
driver.find_element(
By.CSS_SELECTOR,
"button.login-button"
)
38. Locating Form Elements
HTML
<form id="login-form">
<input id="username" name="username" type="text" placeholder="Username">
<input id="password" name="password" type="password" placeholder="Password">
<button id="login">Login</button>
</form>
Python
username = driver.find_element(
By.ID,
"username"
)
password = driver.find_element(
By.ID,
"password"
)
login = driver.find_element(
By.ID,
"login"
)
username.send_keys("testuser")
password.send_keys("Test@123")
login.click()
39. Locating Checkboxes
HTML
<input
type="checkbox"
id="terms"
>
Python
terms = driver.find_element(
By.ID,
"terms"
)
if not terms.is_selected():
terms.click()
40. Locating Radio Buttons
HTML
<input
type="radio"
name="gender"
value="male"
id="male"
>
<input
type="radio"
name="gender"
value="female"
id="female"
>
Python
male = driver.find_element(
By.ID,
"male"
)
male.click()
41. Locating Dropdowns
HTML
<select id="country">
<option value="in">India</option>
<option value="us">United States</option>
</select>
Locate Dropdown
country_element = driver.find_element(
By.ID,
"country"
)
For a standard HTML select element, Selenium's Select class can then be used.
from selenium.webdriver.support.ui import Select
country = Select(
driver.find_element(By.ID, "country")
)
country.select_by_visible_text("India")
42. Locating Buttons
HTML
<button id="submit">
Submit
</button>
ID
driver.find_element(
By.ID,
"submit"
).click()
XPath
driver.find_element(
By.XPATH,
"//button[text()='Submit']"
).click()
CSS
driver.find_element(
By.CSS_SELECTOR,
"#submit"
).click()
43. Locating Links
HTML
<a href="/products">
Products
</a>
Link Text
driver.find_element(
By.LINK_TEXT,
"Products"
).click()
Partial Link Text
driver.find_element(
By.PARTIAL_LINK_TEXT,
"Prod"
).click()
CSS
driver.find_element(
By.CSS_SELECTOR,
"a[href='/products']"
).click()
44. Locating Tables
HTML
<table id="users">
<tr>
<td>Manish</td>
<td>QA</td>
</tr>
</table>
Locate Table
table = driver.find_element(
By.ID,
"users"
)
Locate Rows
rows = table.find_elements(
By.TAG_NAME,
"tr"
)
for row in rows:
print(row.text)
Selenium also supports finding elements from the context of an already located WebElement.
45. Finding Child Elements from a Parent Element
Sometimes it is easier to first locate a parent element and then search for child elements inside it.
HTML
<div id="login-form">
<input name="username">
<input name="password">
</div>
Python
login_form = driver.find_element(
By.ID,
"login-form"
)
inputs = login_form.find_elements(
By.TAG_NAME,
"input"
)
for input_element in inputs:
print(input_element.get_attribute("name"))
46. Locator Chaining Concept
Locator chaining means first finding a parent element and then locating a child element within that parent.
parent = driver.find_element(
By.ID,
"login-form"
)
username = parent.find_element(
By.NAME,
"username"
)
username.send_keys("testuser")
47. Locators with Explicit Wait
Locators are frequently combined with WebDriverWait and expected conditions when elements are loaded dynamically.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
username = wait.until(
EC.visibility_of_element_located(
(By.ID, "username")
)
)
username.send_keys("testuser")
The locator is still the same; the wait controls when Selenium proceeds to interact with the located element.
48. Locators with element_to_be_clickable
login_button = WebDriverWait(
driver,
10
).until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
login_button.click()
49. Locators and Dynamic Web Applications
Modern applications may use JavaScript frameworks and dynamically generate or update elements. Therefore, the locator should target a stable property whenever possible.
Dynamic UI
|
+---- IDs may change
+---- Classes may change
+---- Elements may appear later
+---- DOM may refresh
|
v
Choose Stable Locator
|
v
Use Appropriate Wait
|
v
Interact with Element
50. Relative Locators
Modern Selenium also supports relative locator capabilities in Python. Relative locators can identify an element based on its position relative to another element, such as above, below, to the left, to the right, or near another element.
Import
from selenium.webdriver.support.relative_locator import locate_with
Example
username = driver.find_element(
By.ID,
"username"
)
password = driver.find_element(
locate_with(By.TAG_NAME, "input").below(username)
)
Common Relative Relationships
- above()
- below()
- to_left_of()
- to_right_of()
- near()
51. When to Use Relative Locators
Relative locators can be useful when an element has weak identifying attributes but has a reliable spatial relationship to another element.
Known Element
|
+---- above
|
+---- below
|
+---- left
|
+---- right
|
+---- near
|
v
Target Element
Traditional stable IDs, names, CSS selectors, or XPath expressions should still be considered when they provide a clearer and more maintainable identification method.
52. Locator Validation
Before using a locator in a large automation suite, verify that it identifies the intended element.
Example
element = driver.find_element(
By.ID,
"username"
)
print(element.tag_name)
print(element.get_attribute("id"))
print(element.get_attribute("name"))
53. Testing a Locator
One useful way to test a locator is to temporarily use find_elements() and inspect how many elements match.
elements = driver.find_elements(
By.CSS_SELECTOR,
".login-button"
)
print("Matching elements:", len(elements))
If the intended locator should identify one unique element but the result contains several elements, the locator may need refinement.
54. Unique Locator
A unique locator identifies exactly one intended element.
element = driver.find_element(
By.ID,
"unique-username"
)
For important interactions such as Login, Checkout, Submit, Delete, or Save, a stable and appropriately specific locator is generally desirable.
55. Ambiguous Locator
An ambiguous locator matches multiple elements.
Example
driver.find_elements(
By.TAG_NAME,
"button"
)
This is not necessarily wrong. It is appropriate when the automation needs a collection of buttons. However, if the test needs one specific button, a more specific locator should usually be used.
56. Bad Locator Example
Consider an XPath that depends heavily on the complete DOM hierarchy:
//html/body/div[1]/div[2]/div[1]/form/div[2]/input
This type of locator can become fragile when the page structure changes.
57. Better Locator Example
If the target has a stable ID:
//input[@id='username']
Or:
driver.find_element(
By.ID,
"username"
)
The second version is concise and directly communicates the locator strategy.
58. Locator Best Practices
- Prefer stable and meaningful attributes.
- Use unique IDs when they are stable.
- Use dedicated test attributes when the application provides them.
- Use CSS selectors for concise attribute and class-based identification.
- Use XPath when relationships or text-based conditions make it appropriate.
- Avoid unnecessarily long XPath expressions.
- Avoid selectors based purely on changing visual styles.
- Keep locators centralized in Page Object classes for larger projects.
- Validate that important locators identify the intended element.
- Use explicit waits when elements are dynamically loaded.
- Avoid relying on arbitrary timing delays.
- Review locators when the application's DOM changes.
59. Common Locator Mistakes
- Using an incorrect ID.
- Using multiple class names with By.CLASS_NAME.
- Using unstable dynamic IDs.
- Using absolute XPath unnecessarily.
- Ignoring duplicate elements.
- Using visible text that changes frequently.
- Not checking whether the element is inside an iframe.
- Not waiting for dynamically loaded elements.
- Using an element locator before the required page has loaded.
- Using a locator that depends on unnecessary DOM hierarchy.
60. Locator Debugging
When a locator fails, check the following:
Locator Failure
|
+---- Is URL correct?
|
+---- Is element present?
|
+---- Is locator syntax correct?
|
+---- Is element inside iframe?
|
+---- Is page dynamically loading?
|
+---- Is locator unique?
|
+---- Has DOM changed?
|
+---- Is another element blocking interaction?
|
v
Fix Locator / Synchronization
61. Common Locator Exceptions
| Exception | Possible Locator Problem |
| NoSuchElementException | Locator does not identify an available element. |
| InvalidSelectorException | XPath or CSS selector syntax is invalid. |
| TimeoutException | Element did not satisfy the expected condition within the wait. |
| StaleElementReferenceException | Previously located element is no longer attached to the current DOM. |
62. Complete Locator Example
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get(
"https://www.selenium.dev/selenium/web/web-form.html"
)
text_box = driver.find_element(
By.NAME,
"my-text"
)
text_box.send_keys("Selenium Python")
submit_button = driver.find_element(
By.CSS_SELECTOR,
"button"
)
submit_button.click()
message = driver.find_element(
By.ID,
"message"
)
print("Message:", message.text)
finally:
driver.quit()
63. Complete Example Using Multiple Locators
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
# ID
username = driver.find_element(
By.ID,
"username"
)
# NAME
email = driver.find_element(
By.NAME,
"email"
)
# CLASS NAME
button = driver.find_element(
By.CLASS_NAME,
"submit-button"
)
# TAG NAME
headings = driver.find_elements(
By.TAG_NAME,
"h1"
)
# CSS SELECTOR
password = driver.find_element(
By.CSS_SELECTOR,
"input[type='password']"
)
# XPATH
login = driver.find_element(
By.XPATH,
"//button[text()='Login']"
)
print("Headings:", len(headings))
finally:
driver.quit()
64. Practical Project: Login Page Locators
Consider a login page with the following HTML:
<form id="login-form">
<input
id="username"
name="username"
type="text"
placeholder="Username"
>
<input
id="password"
name="password"
type="password"
placeholder="Password"
>
<button
id="login"
class="login-button"
>
Login
</button>
</form>
Using ID
username = driver.find_element(
By.ID,
"username"
)
Using Name
username = driver.find_element(
By.NAME,
"username"
)
Using CSS
username = driver.find_element(
By.CSS_SELECTOR,
"input#username"
)
Using XPath
username = driver.find_element(
By.XPATH,
"//input[@id='username']"
)
Login Button
login_button = driver.find_element(
By.ID,
"login"
)
login_button.click()
65. Practical Project Flow
Open Login Page
↓
Inspect HTML
↓
Identify Stable Attributes
↓
Create Locators
↓
Find Username
↓
Find Password
↓
Find Login Button
↓
Enter Credentials
↓
Click Login
↓
Validate Dashboard
↓
End Test
66. Page Object Model and Locators
In a professional automation framework, locators are commonly stored inside Page Object classes instead of being repeated throughout every test.
from selenium.webdriver.common.by import By
class LoginPage:
USERNAME = (By.ID, "username")
PASSWORD = (By.ID, "password")
LOGIN_BUTTON = (By.ID, "login")
def __init__(self, driver):
self.driver = driver
def enter_username(self, username):
self.driver.find_element(
*self.USERNAME
).send_keys(username)
def enter_password(self, password):
self.driver.find_element(
*self.PASSWORD
).send_keys(password)
def click_login(self):
self.driver.find_element(
*self.LOGIN_BUTTON
).click()
Test Code
login_page.enter_username("testuser")
login_page.enter_password("Test@123")
login_page.click_login()
67. Locators in a Selenium Project Structure
selenium_project/
|
+-- pages/
| +-- login_page.py
| +-- home_page.py
| +-- checkout_page.py
|
+-- tests/
| +-- test_login.py
| +-- test_search.py
| +-- test_checkout.py
|
+-- utils/
| +-- helpers.py
|
+-- requirements.txt
The Page Object classes can contain the locators and page actions, while test files contain the test scenarios.
68. Locator Strategy Comparison
| Strategy | Best Used For | Example |
| ID | Stable unique IDs | By.ID, "username" |
| NAME | Stable name attributes | By.NAME, "email" |
| CLASS_NAME | Single stable class | By.CLASS_NAME, "login" |
| TAG_NAME | Finding elements by HTML tag | By.TAG_NAME, "button" |
| LINK_TEXT | Exact visible link text | By.LINK_TEXT, "Login" |
| PARTIAL_LINK_TEXT | Partial visible link text | By.PARTIAL_LINK_TEXT, "Log" |
| CSS_SELECTOR | CSS-based attributes, classes, and relationships | By.CSS_SELECTOR, "#login" |
| XPath | Complex attributes, text, and DOM relationships | By.XPATH, "//button[@id='login']" |
69. Interview Questions
Q1. What is a locator in Selenium?
A locator is a strategy used to identify a specific web element or group of elements in the DOM.
Q2. How many traditional locator strategies does Selenium WebDriver provide?
Selenium provides eight traditional locator strategies: ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath.
Q3. What is By in Selenium Python?
By is the Selenium Python class used to specify the locator strategy when finding elements.
Q4. How do you locate an element by ID?
driver.find_element(
By.ID,
"username"
)
Q5. What is the difference between find_element() and find_elements()?
find_element() returns the first matching element, while find_elements() returns a list of matching elements.
Q6. What happens if find_element() cannot find an element?
It raises a NoSuchElementException.
Q7. What happens if find_elements() cannot find any elements?
It returns an empty list.
Q8. What is the difference between CSS Selector and XPath?
CSS Selector uses CSS selector syntax, while XPath uses XPath expressions and can represent complex DOM relationships and conditions.
Q9. Can XPath locate an element using text?
Yes.
driver.find_element(
By.XPATH,
"//button[text()='Login']"
)
Q10. What is a dynamic locator?
A dynamic locator is a locator designed to identify an element even when some parts of its attributes or DOM representation change between executions.
Q11. What is a stable locator?
A stable locator relies on an attribute or relationship that is expected to remain consistent across application changes.
Q12. Can Selenium locate multiple elements?
Yes. Use find_elements().
Q13. Can a WebElement be used to find child elements?
Yes. A located WebElement can be used as the search context for another find_element() or find_elements() call.
Q14. Why should absolute XPath generally be avoided?
Absolute XPath depends heavily on the complete DOM hierarchy and can become fragile when the page structure changes.
Q15. What is a test attribute?
A test attribute is an HTML attribute intentionally provided to make automated element identification more stable, such as data-testid.
70. Quick Revision
| Concept | Syntax |
| Import By | from selenium.webdriver.common.by import By |
| ID | By.ID, "username" |
| Name | By.NAME, "username" |
| Class | By.CLASS_NAME, "login" |
| Tag | By.TAG_NAME, "button" |
| Link Text | By.LINK_TEXT, "Login" |
| Partial Link Text | By.PARTIAL_LINK_TEXT, "Log" |
| CSS | By.CSS_SELECTOR, "#username" |
| XPath | By.XPATH, "//input[@id='username']" |
| One Element | driver.find_element() |
| Multiple Elements | driver.find_elements() |
| Text XPath | //button[text()='Login'] |
| Contains XPath | //button[contains(text(),'Login')] |
| CSS Attribute | input[name='username'] |
| Relative Locator | locate_with(...) |
71. Locator Learning Flow
HTML Basics
↓
DOM Understanding
↓
By Class
↓
ID Locator
↓
Name Locator
↓
Class Name
↓
Tag Name
↓
Link Text
↓
Partial Link Text
↓
CSS Selector
↓
XPath
↓
find_element()
↓
find_elements()
↓
Dynamic Locators
↓
Explicit Wait + Locators
↓
Relative Locators
↓
Page Object Model
↓
Real-World Automation
72. Practical Exercise
Create a Selenium Python script that opens a test website and performs the following tasks:
- Find a text field using ID.
- Find another field using Name.
- Find a button using Class Name.
- Find all links using Tag Name.
- Find a navigation link using Link Text.
- Find a link using Partial Link Text.
- Find an element using CSS Selector.
- Find an element using XPath.
- Print the text of the located elements.
- Click a button.
- Take a screenshot after the operation.
- Close the browser.
73. Final Summary
Locators with Python are the foundation of Selenium WebDriver element interaction. Selenium first identifies an element using a locator and then performs an action on the returned WebElement.
The major traditional locator strategies are ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath. Selenium Python also supports relative locator capabilities.
For reliable automation, choose locators based on stable application attributes, avoid unnecessarily fragile selectors, use appropriate waits for dynamic content, and keep locators organized in Page Object classes in larger frameworks.
74. Course Resources
Selenium Training: https://www.justacademy.co/course-detail/selenium-training
Register for Course Demo: https://www.justacademy.co/register-for-course-demo
Official Selenium Website: https://www.selenium.dev/